<!doctype html>



  


<html class="theme-next pisces use-motion">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>



<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />












  
  
  <link href="/vendors/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/vendors/font-awesome/css/font-awesome.min.css?v=4.4.0" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.0.1" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="Heartbeat,IM," />





  <link rel="alternate" href="/atom.xml" title="crossoverJie's Blog" type="application/atom+xml" />




  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.0.1" />






<meta name="description" content="前言说道“心跳”这个词大家都不陌生，当然不是指男女之间的心跳，而是和长连接相关的。
顾名思义就是证明是否还活着的依据。
什么场景下需要心跳呢？
目前我们接触到的大多是一些基于长连接的应用需要心跳来“保活”。
由于在长连接的场景下，客户端和服务端并不是一直处于通信状态，如果双方长期没有沟通则双方都不清楚对方目前的状态；所以需要发送一段很小的报文告诉对方“我还活着”。">
<meta property="og:type" content="article">
<meta property="og:title" content="长连接的心跳及重连设计">
<meta property="og:url" content="http://crossoverjie.top/2019/01/23/netty/cim03-heartbeat/index.html">
<meta property="og:site_name" content="crossoverJie's Blog">
<meta property="og:description" content="前言说道“心跳”这个词大家都不陌生，当然不是指男女之间的心跳，而是和长连接相关的。
顾名思义就是证明是否还活着的依据。
什么场景下需要心跳呢？
目前我们接触到的大多是一些基于长连接的应用需要心跳来“保活”。
由于在长连接的场景下，客户端和服务端并不是一直处于通信状态，如果双方长期没有沟通则双方都不清楚对方目前的状态；所以需要发送一段很小的报文告诉对方“我还活着”。">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1bed3512ca.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1beda71e1a.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1bedb0c84f.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1bedba4a5f.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1bedc32bf5.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1bedcce886.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1bedd54026.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1bee341616.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1bee3cc343.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1bee453e8c.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1bee4d34ba.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1bee585fbb.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1beeac9619.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1beeb441d9.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1beec116ff.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1beecdc01a.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1beed63443.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1beedd6b0d.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1beee61f44.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1c2fec4fde.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1c301a72b1.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1c304b7104.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1c3070e236.jpg">
<meta property="og:updated_time" content="2019-05-07T17:41:11.289Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="长连接的心跳及重连设计">
<meta name="twitter:description" content="前言说道“心跳”这个词大家都不陌生，当然不是指男女之间的心跳，而是和长连接相关的。
顾名思义就是证明是否还活着的依据。
什么场景下需要心跳呢？
目前我们接触到的大多是一些基于长连接的应用需要心跳来“保活”。
由于在长连接的场景下，客户端和服务端并不是一直处于通信状态，如果双方长期没有沟通则双方都不清楚对方目前的状态；所以需要发送一段很小的报文告诉对方“我还活着”。">
<meta name="twitter:image" content="https://i.loli.net/2019/05/08/5cd1bed3512ca.jpg">



<script type="text/javascript" id="hexo.configuration">
  var NexT = window.NexT || {};
  var CONFIG = {
    scheme: 'Pisces',
    sidebar: {"position":"left","display":"post"},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: 555390,
      author: 'crossoverJie'
    }
  };
</script>




  <link rel="canonical" href="http://crossoverjie.top/2019/01/23/netty/cim03-heartbeat/"/>

  <title> 长连接的心跳及重连设计 | crossoverJie's Blog </title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="en">

  








  <div style="display: none;">
    <script src="https://s6.cnzz.com/stat.php?id=1259025147&web_id=1259025147" type="text/javascript"></script>
  </div>





  
  
    
  

  <div class="container one-collumn sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-meta ">
  

  <div class="custom-logo-site-title">
    <a href="/"  class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <span class="site-title">crossoverJie's Blog</span>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>
  <p class="site-subtitle">baller</p>
</div>

<div class="site-nav-toggle">
  <button>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
  </button>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            Home
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            Categories
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            About
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            Archives
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            Tags
          </a>
        </li>
      
        
        <li class="menu-item menu-item-photo">
          <a href="/favourite" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-photo"></i> <br />
            
            photo
          </a>
        </li>
      
        
        <li class="menu-item menu-item-jcsprout">
          <a href="https://crossoverjie.top/JCSprout/#/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-leaf"></i> <br />
            
            JCSprout
          </a>
        </li>
      
        
        <li class="menu-item menu-item-cicada">
          <a href="https://github.com/TogetherOS/cicada" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-github"></i> <br />
            
            cicada
          </a>
        </li>
      
        
        <li class="menu-item menu-item-cim">
          <a href="https://github.com/crossoverjie/cim" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-far fa-comment"></i> <br />
            
            CIM
          </a>
        </li>
      
        
        <li class="menu-item menu-item-vlog">
          <a href="https://space.bilibili.com/42339430" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-youtube"></i> <br />
            
            Vlog
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="#" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            Search
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup">
 <span class="search-icon fa fa-search"></span>
 <input type="text" id="local-search-input">
 <div id="local-search-result"></div>
 <span class="popup-btn-close">close</span>
</div>


    </div>
  
</nav>

 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  
  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                长连接的心跳及重连设计
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            <span class="post-meta-item-icon">
              <i class="fa fa-calendar-o"></i>
            </span>
            <span class="post-meta-item-text">Posted on</span>
            <time itemprop="dateCreated" datetime="2019-01-23T08:08:14+08:00" content="2019-01-23">
              2019-01-23
            </time>
          </span>

          
            <span class="post-category" >
              &nbsp; | &nbsp;
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">In</span>
              
                <span itemprop="about" itemscope itemtype="https://schema.org/Thing">
                  <a href="/categories/Netty/" itemprop="url" rel="index">
                    <span itemprop="name">Netty</span>
                  </a>
                </span>

                
                
                  , 
                

              
                <span itemprop="about" itemscope itemtype="https://schema.org/Thing">
                  <a href="/categories/Netty/cim/" itemprop="url" rel="index">
                    <span itemprop="name">cim</span>
                  </a>
                </span>

                
                

              
            </span>
          

          
            
              <span class="post-comments-count">
                &nbsp; | &nbsp;
                <a href="/2019/01/23/netty/cim03-heartbeat/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count disqus-comment-count" data-disqus-identifier="2019/01/23/netty/cim03-heartbeat/" itemprop="commentsCount"></span>
                </a>
              </span>
            
          

          

          
          
             <span id="/2019/01/23/netty/cim03-heartbeat/" class="leancloud_visitors" data-flag-title="长连接的心跳及重连设计">
               &nbsp; | &nbsp;
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               <span class="post-meta-item-text">visitors </span>
               <span class="leancloud-visitors-count"></span>
              </span>
          

          
              &nbsp; | &nbsp;
              <span class="page-pv">本文总阅读量
              <span class="busuanzi-value" id="busuanzi_value_page_pv" ></span>次
              </span>
          
        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        <p><img src="https://i.loli.net/2019/05/08/5cd1bed3512ca.jpg" alt=""></p>
<h1 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h1><p>说道“心跳”这个词大家都不陌生，当然不是指男女之间的心跳，而是和长连接相关的。</p>
<p>顾名思义就是证明是否还活着的依据。</p>
<p>什么场景下需要心跳呢？</p>
<p>目前我们接触到的大多是一些基于长连接的应用需要心跳来“保活”。</p>
<p>由于在长连接的场景下，客户端和服务端并不是一直处于通信状态，如果双方长期没有沟通则双方都不清楚对方目前的状态；所以需要发送一段很小的报文告诉对方<code>“我还活着”</code>。</p>
<a id="more"></a>
<p>同时还有另外几个目的：</p>
<ul>
<li>服务端检测到某个客户端迟迟没有心跳过来可以主动关闭通道，让它下线。</li>
<li>客户端检测到某个服务端迟迟没有响应心跳也能重连获取一个新的连接。</li>
</ul>
<p>正好借着在 <a href="https://github.com/crossoverJie/cim" target="_blank" rel="external">cim</a>有这样两个需求来聊一聊。</p>
<h1 id="心跳实现方式"><a href="#心跳实现方式" class="headerlink" title="心跳实现方式"></a>心跳实现方式</h1><p>心跳其实有两种实现方式：</p>
<ul>
<li><code>TCP</code> 协议实现（<code>keepalive</code> 机制）。</li>
<li>应用层自己实现。</li>
</ul>
<p>由于 <code>TCP</code> 协议过于底层，对于开发者来说维护性、灵活度都比较差同时还依赖于操作系统。</p>
<p>所以我们这里所讨论的都是应用层的实现。</p>
<hr>
<p><img src="https://i.loli.net/2019/05/08/5cd1beda71e1a.jpg" alt=""></p>
<p>如上图所示，在应用层通常是由客户端发送一个心跳包 <code>ping</code> 到服务端，服务端收到后响应一个 <code>pong</code> 表明双方都活得好好的。</p>
<p>一旦其中一端延迟 N 个时间窗口没有收到消息则进行不同的处理。</p>
<h1 id="客户端自动重连"><a href="#客户端自动重连" class="headerlink" title="客户端自动重连"></a>客户端自动重连</h1><p>先拿客户端来说吧，每隔一段时间客户端向服务端发送一个心跳包，同时收到服务端的响应。</p>
<p>常规的实现应当是：</p>
<ul>
<li>开启一个定时任务，定期发送心跳包。</li>
<li>收到服务端响应后更新本地时间。</li>
<li>再有一个定时任务定期检测这个<code>“本地时间”</code>是否超过阈值。</li>
<li>超过后则认为服务端出现故障，需要重连。</li>
</ul>
<p>这样确实也能实现心跳，但并不友好。</p>
<p>在正常的客户端和服务端通信的情况下，定时任务依然会发送心跳包；这样就显得没有意义，有些多余。</p>
<p>所以理想的情况应当是客户端收到的写消息空闲时才发送这个心跳包去确认服务端是否健在。</p>
<p>好消息是 <code>Netty</code> 已经为我们考虑到了这点，自带了一个开箱即用的 <code>IdleStateHandler</code> 专门用于心跳处理。</p>
<p>来看看 <code>cim</code> 中的实现：</p>
<p><img src="https://i.loli.net/2019/05/08/5cd1bedb0c84f.jpg" alt=""></p>
<p>在 <code>pipeline</code> 中加入了一个 10秒没有收到写消息的 <code>IdleStateHandler</code>，到时他会回调 <code>ChannelInboundHandler</code> 中的 <code>userEventTriggered</code> 方法。</p>
<p><img src="https://i.loli.net/2019/05/08/5cd1bedba4a5f.jpg" alt=""></p>
<p>所以一旦写超时就立马向服务端发送一个心跳（做的更完善应当在心跳发送失败后有一定的重试次数）；</p>
<p>这样也就只有在空闲时候才会发送心跳包。</p>
<p>但一旦间隔许久没有收到服务端响应进行重连的逻辑应当写在哪里呢？</p>
<p>先来看这个示例：</p>
<p>当收到服务端响应的 pong 消息时，就在当前 Channel 上记录一个时间，也就是说后续可以在定时任务中取出这个时间和当前时间的差额来判断是否超过阈值。</p>
<p>超过则重连。</p>
<p><img src="https://i.loli.net/2019/05/08/5cd1bedc32bf5.jpg" alt=""><br><img src="https://i.loli.net/2019/05/08/5cd1bedcce886.jpg" alt=""></p>
<p>同时在每次心跳时候都用当前时间和之前服务端响应绑定到 <code>Channel</code> 上的时间相减判断是否需要重连即可。</p>
<p>也就是  <code>heartBeatHandler.process(ctx);</code> 的执行逻辑。</p>
<p>伪代码如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div></pre></td><td class="code"><pre><div class="line"><span class="meta">@Override</span></div><div class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">process</span><span class="params">(ChannelHandlerContext ctx)</span> <span class="keyword">throws</span> Exception </span>&#123;</div><div class="line"></div><div class="line">    <span class="keyword">long</span> heartBeatTime = appConfiguration.getHeartBeatTime() * <span class="number">1000</span>;</div><div class="line">    </div><div class="line">    Long lastReadTime = NettyAttrUtil.getReaderTime(ctx.channel());</div><div class="line">    <span class="keyword">long</span> now = System.currentTimeMillis();</div><div class="line">    <span class="keyword">if</span> (lastReadTime != <span class="keyword">null</span> &amp;&amp; now - lastReadTime &gt; heartBeatTime)&#123;</div><div class="line">        reconnect();</div><div class="line">    &#125;</div><div class="line"></div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h2 id="IdleStateHandler-误区"><a href="#IdleStateHandler-误区" class="headerlink" title="IdleStateHandler 误区"></a>IdleStateHandler 误区</h2><p>一切看起来也没毛病，但实际上却没有这样实现重连逻辑。</p>
<p>最主要的问题还是对 <code>IdleStateHandler</code> 理解有误。</p>
<p>我们假设下面的场景：</p>
<ol>
<li>客户端通过登录连上了服务端并保持长连接，一切正常的情况下双方各发心跳包保持连接。</li>
<li>这时服务端突入出现 down 机，那么理想情况下应当是客户端迟迟没有收到服务端的响应从而 <code>userEventTriggered</code> 执行定时任务。</li>
<li>判断<code>当前时间 - UpdateWriteTime &gt; 阈值</code> 时进行重连。</li>
</ol>
<p>但却事与愿违，并不会执行 2、3两步。</p>
<p>因为一旦服务端 <code>down</code> 机、或者是与客户端的网络断开则会回调客户端的 <code>channelInactive</code> 事件。</p>
<p><code>IdleStateHandler</code> 作为一个 <code>ChannelInbound</code> 也重写了 <code>channelInactive()</code> 方法。</p>
<p><img src="https://i.loli.net/2019/05/08/5cd1bedd54026.jpg" alt=""><br><img src="https://i.loli.net/2019/05/08/5cd1bee341616.jpg" alt=""></p>
<p>这里的 <code>destroy()</code> 方法会把之前开启的定时任务都给取消掉。</p>
<p><strong>所以就不会再有任何的定时任务执行了，也就不会有机会执行这个重连业务</strong>。</p>
<h2 id="靠谱实现"><a href="#靠谱实现" class="headerlink" title="靠谱实现"></a>靠谱实现</h2><p>因此我们得有一个单独的线程来判断是否需要重连，不依赖于 <code>IdleStateHandler</code>。</p>
<p>于是 <code>cim</code> 在客户端感知到网络断开时就会开启一个定时任务：</p>
<p><img src="https://i.loli.net/2019/05/08/5cd1bee3cc343.jpg" alt=""></p>
<blockquote>
<p>之所以不在客户端启动就开启，是为了节省一点线程消耗。网络问题虽然不可避免，但在需要的时候开启更能节省资源。</p>
</blockquote>
<p><img src="https://i.loli.net/2019/05/08/5cd1bee453e8c.jpg" alt=""></p>
<p><img src="https://i.loli.net/2019/05/08/5cd1bee4d34ba.jpg" alt=""></p>
<p>在这个任务重其实就是执行了重连，限于篇幅具体代码就不贴了，感兴趣的可以自行查阅。</p>
<p>同时来验证一下效果。</p>
<blockquote>
<p>启动两个服务端，再启动客户端连接上一台并保持长连接。这时突然手动关闭一台服务，客户端可以自动重连到可用的那台服务节点。</p>
</blockquote>
<p><img src="https://i.loli.net/2019/05/08/5cd1bee585fbb.jpg" alt=""><br><img src="https://i.loli.net/2019/05/08/5cd1beeac9619.jpg" alt=""></p>
<p>启动客户端后服务端也能收到正常的 <code>ping</code> 消息。</p>
<p>利用 <code>:info</code> 命令查看当前客户端的链接状态发现连的是 <code>9000</code>端口。</p>
<p><img src="https://i.loli.net/2019/05/08/5cd1beeb441d9.jpg" alt=""></p>
<blockquote>
<p>:info 是一个新增命令，可以查看一些客户端信息。</p>
</blockquote>
<p>这时我关掉连接上的这台节点。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">kill -9 2142</div></pre></td></tr></table></figure>
<p><img src="https://i.loli.net/2019/05/08/5cd1beec116ff.jpg" alt=""><br><img src="https://i.loli.net/2019/05/08/5cd1beecdc01a.jpg" alt=""></p>
<p>这时客户端会自动重连到可用的那台节点。<br>这个节点也收到了上线日志以及心跳包。</p>
<h1 id="服务端自动剔除离线客户端"><a href="#服务端自动剔除离线客户端" class="headerlink" title="服务端自动剔除离线客户端"></a>服务端自动剔除离线客户端</h1><p>现在来看看服务端，它要实现的效果就是延迟 N 秒没有收到客户端的 <code>ping</code> 包则认为客户端下线了，在 <code>cim</code> 的场景下就需要把他踢掉置于离线状态。</p>
<h2 id="消息发送误区"><a href="#消息发送误区" class="headerlink" title="消息发送误区"></a>消息发送误区</h2><p>这里依然有一个误区，在调用 <code>ctx.writeAndFlush()</code> 发送消息获取回调时。</p>
<p>其中是 <code>isSuccess</code> 并不能作为消息发送成功与否的标准。</p>
<p><img src="https://i.loli.net/2019/05/08/5cd1beed63443.jpg" alt=""></p>
<p>也就是说即便是客户端直接断网，服务端这里发送消息后拿到的 <code>success</code> 依旧是 <code>true</code>。</p>
<p><strong>这是因为这里的 <code>success</code> 只是告知我们消息写入了 <code>TCP</code> 缓冲区成功了而已。</strong></p>
<p>和我之前有着一样错误理解的不在少数，这是 <code>Netty</code> 官方给的回复。</p>
<p><img src="https://i.loli.net/2019/05/08/5cd1beedd6b0d.jpg" alt=""></p>
<p>相关 <code>issue</code>：</p>
<p><a href="https://github.com/netty/netty/issues/4915" target="_blank" rel="external">https://github.com/netty/netty/issues/4915</a></p>
<blockquote>
<p>同时感谢 95老徐以及闪电侠的一起排查。</p>
</blockquote>
<p>所以我们不能依据此来关闭客户端的连接，而是要像上文一样判断 <code>Channel</code> 上绑定的时间与当前时间只差是否超过了阈值。</p>
<p><img src="https://i.loli.net/2019/05/08/5cd1beee61f44.jpg" alt=""><br><img src="https://i.loli.net/2019/05/08/5cd1c2fec4fde.jpg" alt=""><br><img src="https://i.loli.net/2019/05/08/5cd1c301a72b1.jpg" alt=""></p>
<p>以上则是 <code>cim</code> 服务端的实现，逻辑和开头说的一致，也和 <code>Dubbo</code> 的心跳机制有些类似。</p>
<p>于是来做个试验：正常通信的客户端和服务端，当我把客户端直接断网时，服务端会自动剔除客户端。</p>
<p><img src="https://i.loli.net/2019/05/08/5cd1c304b7104.jpg" alt=""><br><img src="https://i.loli.net/2019/05/08/5cd1c3070e236.jpg" alt=""></p>
<h1 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h1><p>这样就实现了文初的两个要求。</p>
<ul>
<li>服务端检测到某个客户端迟迟没有心跳过来可以主动关闭通道，让它下线。</li>
<li>客户端检测到某个服务端迟迟没有响应心跳也能重连获取一个新的连接。</li>
</ul>
<p>同时也踩了两个误区，坑一个人踩就可以了，希望看过本文的都有所收获避免踩坑。</p>
<p>本文所有相关代码都在此处，感兴趣的可以自行查看：</p>
<p><a href="https://github.com/crossoverJie/cim" target="_blank" rel="external">https://github.com/crossoverJie/cim</a></p>
<p>如果本文对你有所帮助还请不吝转发。</p>

      
    </div>

    <div>
      
        
<div id="wechat_subscriber" style="display: block； padding: 10px 0; margin: 20px auto; width: 100%; text-align: center">
    <img id="wechat_subscriber_qcode" src="/uploads/weixinfooter1.jpg" alt="crossoverJie wechat" style="width: 200px; max-width: 100%;"/>
    <div>我很有眼光！</div>
</div>

      
    </div>

    <div>
      
        
  <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
    <div>请我吃🍗</div>
    <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
      <span>赏</span>
    </button>
    <div id="QR" style="display: none;">
      
        <div id="wechat" style="display: inline-block">
          <img id="wechat_qr" src="/weixin-reward-image.jpg" alt="crossoverJie WeChat Pay"/>
          <p>微信打赏</p>
        </div>
      
      
        <div id="alipay" style="display: inline-block">
          <img id="alipay_qr" src="/alipay-reward-image.jpg" alt="crossoverJie Alipay"/>
          <p>支付宝打赏</p>
        </div>
      
    </div>
  </div>


      
    </div>

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Heartbeat/" rel="tag">#Heartbeat</a>
          
            <a href="/tags/IM/" rel="tag">#IM</a>
          
        </div>
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2019/01/14/netty/cim02-v1.0.1/" rel="next" title="为自己搭建一个分布式 IM 系统二【从查找算法聊起】">
                <i class="fa fa-chevron-left"></i> 为自己搭建一个分布式 IM 系统二【从查找算法聊起】
              </a>
            
          </div>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2019/01/30/java-senior/design-if-else/" rel="prev" title="利用策略模式优化过多 if else 代码">
                利用策略模式优化过多 if else 代码 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          

  <p>热评文章</p>
  <div class="ds-top-threads" data-range="weekly" data-num-items="4"></div>


          
  <div class="comments" id="comments">
    
      <div id="disqus_thread">
        <noscript>
          Please enable JavaScript to view the
          <a href="//disqus.com/?ref_noscript">comments powered by Disqus.</a>
        </noscript>
      </div>
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            Table of Contents
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            Overview
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel ">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/uploads/crossoverjie.jpg"
               alt="crossoverJie" />
          <p class="site-author-name" itemprop="name">crossoverJie</p>
          <p class="site-description motion-element" itemprop="description">You never know what you can do till you try.</p>
        </div>
        <nav class="site-state motion-element">
          <div class="site-state-item site-state-posts">
            <a href="/archives">
              <span class="site-state-item-count">116</span>
              <span class="site-state-item-name">posts</span>
            </a>
          </div>

          
            <div class="site-state-item site-state-categories">
              <a href="/categories">
                <span class="site-state-item-count">45</span>
                <span class="site-state-item-name">categories</span>
              </a>
            </div>
          

          
            <div class="site-state-item site-state-tags">
              <a href="/tags">
                <span class="site-state-item-count">109</span>
                <span class="site-state-item-name">tags</span>
              </a>
            </div>
          

        </nav>

        
          <div class="feed-link motion-element">
            <a href="/atom.xml" rel="alternate">
              <i class="fa fa-rss"></i>
              RSS
            </a>
          </div>
        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/crossoverJie" target="_blank" title="GitHub">
                  
                    <i class="fa fa-fw fa-github"></i>
                  
                  GitHub
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="http://www.jianshu.com/users/e2d07947c112/latest_articles" target="_blank" title="简书">
                  
                    <i class="fa fa-fw fa-book"></i>
                  
                  简书
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://juejin.im/user/576d4aaf7db2a20054ea4544" target="_blank" title="掘金">
                  
                    <i class="fa fa-fw fa-bookmark"></i>
                  
                  掘金
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://twitter.com/crossoverJie" target="_blank" title="Twitter">
                  
                    <i class="fa fa-fw fa-twitter"></i>
                  
                  Twitter
                </a>
              </span>
            
          
        </div>

        
        

        
        
          <div class="links-of-blogroll motion-element links-of-blogroll-inline">
            <div class="links-of-blogroll-title">
              <i class="fa  fa-fw fa-globe"></i>
              友情链接
            </div>
            <ul class="links-of-blogroll-list">
              
                <li class="links-of-blogroll-item">
                  <a href="http://wuchong.me" title="Jark's Blog" target="_blank">Jark's Blog</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://tengj.top" title="嘟嘟独立博客" target="_blank">嘟嘟独立博客</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://yemengying.com/" title="Giraffe Home" target="_blank">Giraffe Home</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="https://blog.jamespan.me/" title="潘小鶸(ruò)" target="_blank">潘小鶸(ruò)</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://fangjian0423.github.io/" title="Format's Notes" target="_blank">Format's Notes</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="https://yuzhouwan.com/" title="Benedict Jin" target="_blank">Benedict Jin</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://blog.didispace.com/" title="程序猿DD" target="_blank">程序猿DD</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="https://blog.52itstyle.vip/" title="小柒博客" target="_blank">小柒博客</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://cmsblogs.com/" title="Java技术驿站" target="_blank">Java技术驿站</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="https://vim.ink/" title="vim 教程网" target="_blank">vim 教程网</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="https://www.jitwxs.cn" title="jitwxs" target="_blank">jitwxs</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://www.javaboy.org" title="江南一点雨" target="_blank">江南一点雨</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://www.liangsonghua.me" title="松花皮蛋的黑板报" target="_blank">松花皮蛋的黑板报</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="https://www.fi-ads.com" title="Future iDeal" target="_blank">Future iDeal</a>
                </li>
              
            </ul>
          </div>
        

      </section>

      
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">
            
              
            
            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#前言"><span class="nav-number">1.</span> <span class="nav-text">前言</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#心跳实现方式"><span class="nav-number">2.</span> <span class="nav-text">心跳实现方式</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#客户端自动重连"><span class="nav-number">3.</span> <span class="nav-text">客户端自动重连</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#IdleStateHandler-误区"><span class="nav-number">3.1.</span> <span class="nav-text">IdleStateHandler 误区</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#靠谱实现"><span class="nav-number">3.2.</span> <span class="nav-text">靠谱实现</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#服务端自动剔除离线客户端"><span class="nav-number">4.</span> <span class="nav-text">服务端自动剔除离线客户端</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#消息发送误区"><span class="nav-number">4.1.</span> <span class="nav-text">消息发送误区</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#总结"><span class="nav-number">5.</span> <span class="nav-text">总结</span></a></li></ol></div>
            
          </div>
        </section>
      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy;  2016 - 
  <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">crossoverJie</span>
</div>

<div class="powered-by">
  Powered by <a class="theme-link" href="http://hexo.io">Hexo</a>
</div>

<div class="theme-info">
  Theme -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Pisces
  </a>
</div>

        

<div class="busuanzi-count">

  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv"><i class="fa fa-user"></i><span class="busuanzi-value" id="busuanzi_value_site_uv"></span>人数</span>
  

  
    <span class="site-pv">您是第<span class="busuanzi-value" id="busuanzi_value_site_pv"></span>位童鞋</span>
  
  
</div>



        
      </div>
    </footer>

    <div class="back-to-top">
      <i class="fa fa-arrow-up"></i>
    </div>
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  



  
  <script type="text/javascript" src="/vendors/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/vendors/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/vendors/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/vendors/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/vendors/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/vendors/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.0.1"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.0.1"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.0.1"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.0.1"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.0.1"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.0.1"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.0.1"></script>



  



  

    <script type="text/javascript">
      var disqus_shortname = 'crossoverjie';
      var disqus_identifier = '2019/01/23/netty/cim03-heartbeat/';
      var disqus_title = "长连接的心跳及重连设计";
      var disqus_url = 'http://crossoverjie.top/2019/01/23/netty/cim03-heartbeat/';

      function run_disqus_script(disqus_script){
        var dsq = document.createElement('script');
        dsq.type = 'text/javascript';
        dsq.async = true;
        dsq.src = '//' + disqus_shortname + '.disqus.com/' + disqus_script;
        (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
      }

      run_disqus_script('count.js');
      
        run_disqus_script('embed.js');
      
    </script>
  




  
  
  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length == 0) {
       search_path = "search.xml";
    }
    var path = "/" + search_path;
    // monitor main search box;

    function proceedsearch() {
      $("body").append('<div class="popoverlay">').css('overflow', 'hidden');
      $('.popup').toggle();

    }
    // search function;
    var searchFunc = function(path, search_id, content_id) {
    'use strict';
    $.ajax({
        url: path,
        dataType: "xml",
        async: true,
        success: function( xmlResponse ) {
            // get the contents from search data
            isfetched = true;
            $('.popup').detach().appendTo('.header-inner');
            var datas = $( "entry", xmlResponse ).map(function() {
                return {
                    title: $( "title", this ).text(),
                    content: $("content",this).text(),
                    url: $( "url" , this).text()
                };
            }).get();
            var $input = document.getElementById(search_id);
            var $resultContent = document.getElementById(content_id);
            $input.addEventListener('input', function(){
                var matchcounts = 0;
                var str='<ul class=\"search-result-list\">';                
                var keywords = this.value.trim().toLowerCase().split(/[\s\-]+/);
                $resultContent.innerHTML = "";
                if (this.value.trim().length > 1) {
                // perform local searching
                datas.forEach(function(data) {
                    var isMatch = true;
                    var content_index = [];
                    var data_title = data.title.trim().toLowerCase();
                    var data_content = data.content.trim().replace(/<[^>]+>/g,"").toLowerCase();
                    var data_url = data.url;
                    var index_title = -1;
                    var index_content = -1;
                    var first_occur = -1;
                    // only match artiles with not empty titles and contents
                    if(data_title != '' && data_content != '') {
                        keywords.forEach(function(keyword, i) {
                            index_title = data_title.indexOf(keyword);
                            index_content = data_content.indexOf(keyword);
                            if( index_title < 0 && index_content < 0 ){
                                isMatch = false;
                            } else {
                                if (index_content < 0) {
                                    index_content = 0;
                                }
                                if (i == 0) {
                                    first_occur = index_content;
                                }
                            }
                        });
                    }
                    // show search results
                    if (isMatch) {
                        matchcounts += 1;
                        str += "<li><a href='"+ data_url +"' class='search-result-title'>"+ data_title +"</a>";
                        var content = data.content.trim().replace(/<[^>]+>/g,"");
                        if (first_occur >= 0) {
                            // cut out 100 characters
                            var start = first_occur - 20;
                            var end = first_occur + 80;
                            if(start < 0){
                                start = 0;
                            }
                            if(start == 0){
                                end = 50;
                            }
                            if(end > content.length){
                                end = content.length;
                            }
                            var match_content = content.substring(start, end);
                            // highlight all keywords
                            keywords.forEach(function(keyword){
                                var regS = new RegExp(keyword, "gi");
                                match_content = match_content.replace(regS, "<b class=\"search-keyword\">"+keyword+"</b>");
                            });
                            
                            str += "<p class=\"search-result\">" + match_content +"...</p>"
                        }
                        str += "</li>";
                    }
                })};
                str += "</ul>";
                if (matchcounts == 0) { str = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>' }
                if (keywords == "") { str = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>' }
                $resultContent.innerHTML = str;
            });
            proceedsearch();
        }
    });}

    // handle and trigger popup window;
    $('.popup-trigger').mousedown(function(e) {
      e.stopPropagation();
      if (isfetched == false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };

    });

    $('.popup-btn-close').click(function(e){
      $('.popup').hide();
      $(".popoverlay").remove();
      $('body').css('overflow', '');
    });
    $('.popup').click(function(e){
      e.stopPropagation();
    });
  </script>

  

  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.1.js"></script>
  <script>AV.initialize("Qv6ckEtL1pe3PJD10qoOLKtg-gzGzoHsz", "NXiHFodQfmI8oxkK6IThhjrF");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  
<script type="text/javascript" src="/js/src/particle.js" count="50" zindex="-2" opacity="1" color="0,104,183"></script>
</body>
</html>
